package com.mx.restful.utils;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.mx.restful.beans.HttpMethod;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class RequestUtils {

    private static final int DEFAULT_TIMEOUT = 30 * 1000;

    public static String request(String url, HttpMethod method, String headers, String params) {
        if (method == null) {
            return "method is null";
        }
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = "http://" + url;
        }
        HttpRequest httpRequest = HttpUtil.createRequest(Method.valueOf(method.name()), url);
        Map<String, String> headMap = JsonUtil.formatMapString(headers);
        if (MapUtil.isNotEmpty(headMap)) {
            headMap.forEach((s, o) -> httpRequest.header(s, o));

        }
        Map<String, Object> bodyMap = JsonUtil.formatMapObject(params);
        if (MapUtil.isNotEmpty(bodyMap)) {
            bodyMap.forEach(httpRequest::form);
        }
        return httpRequest.execute().body();

    }

    /**
     * get
     *
     * @param url
     * @param headers
     * @param params
     * @return
     */
    private static String get(String url, Map<String, String> headers, Map<String, Object> params) {
        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String resultString = null;
        CloseableHttpResponse response = null;
        try {
            //创建uri
            URIBuilder builder = new URIBuilder(completed(url));
            if (params != null) {
                //uri添加参数
                for (String key : params.keySet()) {
                    builder.addParameter(key, String.valueOf(params.get(key)));
                }
            }
            URI uri = builder.build();
            //创建hTTP get请求
            HttpGet httpGet = new HttpGet(uri);
            //设置超时时间
            int timeoutTmp = DEFAULT_TIMEOUT;

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpGet.setConfig(requestConfig);
            //设置头信息
            if (null != headers) {
                for (String key : headers.keySet()) {
                    httpGet.setHeader(key, headers.get(key));
                }
            }
            //执行请求
            response = httpClient.execute(httpGet);
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            release(response, httpClient);
        }
        return resultString;

    }

    /**
     * post
     *
     * @param url
     * @param headers
     * @param params
     * @return
     */
    public static String post(String url, Map<String, String> headers, Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            //创建http post请求
            HttpPost httpPost = new HttpPost(completed(url));
            //设置超时时间
            int timeoutTmp = DEFAULT_TIMEOUT;

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpPost.setConfig(requestConfig);
            //设置参数信息
            if (params != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : params.keySet()) {
                    paramList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
                //模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
                httpPost.setEntity(entity);
            }
            //设置头信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPost.setHeader(key, headers.get(key));
                }
            }
            //执行http请求
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            release(response, httpClient);
        }
        return resultString;
    }

    /**
     * put
     *
     * @param url
     * @param headers
     * @param params
     * @return
     */
    public static String put(String url, Map<String, String> headers, String params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            //创建http post请求
            HttpPut httpPut = new HttpPut(completed(url));
            //设置超时时间
            int timeoutTmp = DEFAULT_TIMEOUT;

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpPut.setConfig(requestConfig);
            //设置参数信息
            if (params != null) {
                StringEntity entity = new StringEntity(params, ContentType.APPLICATION_JSON);

                httpPut.setEntity(entity);
            }
            //设置头信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPut.setHeader(key, headers.get(key));
                }
            }
            //执行http请求
            response = httpClient.execute(httpPut);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            release(response, httpClient);
        }
        return resultString;
    }

    /**
     * delete
     *
     * @param url
     * @param headers
     * @param params
     * @return
     */
    public static String delete(String url, Map<String, String> headers, Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {

            URIBuilder builder = new URIBuilder(url);
            //设置参数信息
            if (params != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : params.keySet()) {
                    paramList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
                builder.addParameters(paramList);
            }
            URI uri = builder.build();
            // 创建Http Delete请求
            HttpDelete httpDelete = new HttpDelete(uri);
            //设置超时时间
            int timeoutTmp = DEFAULT_TIMEOUT;

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpDelete.setConfig(requestConfig);


            //设置头信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpDelete.setHeader(key, headers.get(key));
                }
            }
            //执行http请求
            response = httpClient.execute(httpDelete);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            release(response, httpClient);
        }
        return resultString;
    }

    /**
     * options
     *
     * @param url
     * @param headers
     * @param params
     * @return
     */
    public static String options(String url, Map<String, String> headers, Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            com.mx.restful.utils.http.method.HttpOptions httpOptions = new com.mx.restful.utils.http.method.HttpOptions(completed(url));
            //设置超时时间
            int timeoutTmp = DEFAULT_TIMEOUT;

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpOptions.setConfig(requestConfig);
            //设置参数信息
            if (params != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : params.keySet()) {
                    paramList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
                //模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
                httpOptions.setEntity(entity);
            }
            //设置头信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpOptions.setHeader(key, headers.get(key));
                }
            }
            //执行http请求
            response = httpClient.execute(httpOptions);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            release(response, httpClient);
        }
        return resultString;
    }

    /**
     * head
     *
     * @param url
     * @param headers
     * @param params
     * @return
     */
    public static String head(String url, Map<String, String> headers, Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            com.mx.restful.utils.http.method.HttpHead httpHead = new com.mx.restful.utils.http.method.HttpHead(completed(url));
            //设置超时时间
            int timeoutTmp = DEFAULT_TIMEOUT;

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpHead.setConfig(requestConfig);
            //设置参数信息
            if (params != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : params.keySet()) {
                    paramList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
                //模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
                httpHead.setEntity(entity);
            }
            //设置头信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpHead.setHeader(key, headers.get(key));
                }
            }
            //执行http请求
            response = httpClient.execute(httpHead);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            release(response, httpClient);
        }
        return resultString;
    }


    /**
     * trace
     *
     * @param url
     * @param headers
     * @param params
     * @return
     */
    public static String trace(String url, Map<String, String> headers, Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            com.mx.restful.utils.http.method.HttpTrace httpTrace = new com.mx.restful.utils.http.method.HttpTrace(completed(url));
            //设置超时时间
            int timeoutTmp = DEFAULT_TIMEOUT;

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpTrace.setConfig(requestConfig);
            //设置参数信息
            if (params != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : params.keySet()) {
                    paramList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
                //模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
                httpTrace.setEntity(entity);
            }
            //设置头信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpTrace.setHeader(key, headers.get(key));
                }
            }
            //执行http请求
            response = httpClient.execute(httpTrace);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            release(response, httpClient);
        }
        return resultString;
    }

    /**
     * patch
     *
     * @param url
     * @param headers
     * @param params
     * @return
     */
    public static String patch(String url, Map<String, String> headers, Map<String, Object> params) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpPatch httpPatch = new HttpPatch(completed(url));
            //设置超时时间
            int timeoutTmp = DEFAULT_TIMEOUT;

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpPatch.setConfig(requestConfig);
            //设置参数信息
            if (params != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : params.keySet()) {
                    paramList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
                //模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
                httpPatch.setEntity(entity);
            }
            //设置头信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPatch.setHeader(key, headers.get(key));
                }
            }
            //执行http请求
            response = httpClient.execute(httpPatch);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            release(response, httpClient);
        }
        return resultString;
    }


    private static void release(CloseableHttpResponse response, CloseableHttpClient httpClient) {
        try {
            if (null != response) {
                response.close();
            }
            if (null != httpClient) {
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String completed(String url) {
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            url = "http://" + url;
        }
        return url;
    }


    private static String toString(HttpEntity entity) {
        String result = null;
        try {
            result = EntityUtils.toString(entity, Charset.forName("UTF-8"));

        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
}
